package com.qimu.saiyou.consumer;

import com.qimu.saiyou.config.DelayExchangeConfig;
import com.qimu.saiyou.model.entity.*;
import com.qimu.saiyou.service.*;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: FeiXiang
 * @Date: 2023/07/21 06:13:02
 * @Version: 1.0
 * @Description:
 */
@Component
@Slf4j
public class UserPaperEndQueueConsumer {
    @Resource
    private UserPaperService userPaperService;
    @Resource
    private CompeteExamService competeExamService;
    @Resource
    private UserPaperAnswerService userPaperAnswerService;
    @Resource
    private QuestionAnswerService questionAnswerService;
    @Resource
    private QuestionService questionService;
    @Resource
    private PaperQuestionService paperQuestionService;
    @Resource
    private ExamPaperService examPaperService;


    @SneakyThrows //时间一到 提交分数
    @Transactional(rollbackFor = Exception.class)
    @RabbitListener(queues = DelayExchangeConfig.END_DELAY_USER_PAPER_QUEUE, ackMode = "MANUAL")
    public void deadline(Message message, Channel channel) {
        try {
            String id = new String(message.getBody());
            log.info("用户考试结束，用户考试id:{}", id);
            UserPaper userPaper = userPaperService.getById(id);
            if (ObjectUtils.isEmpty(userPaper)) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            if (("submit".equals(userPaper.getState()))) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            CompeteExam competeExam = competeExamService.getById(userPaper.getExamId());
            if (competeExam == null) {
                log.error("试卷保存失败");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            Long paperId = competeExam.getPaperId();
            ExamPaper examPaper = examPaperService.getById(paperId);
            if (examPaper == null) {
                log.error("试卷保存失败");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            doSumbit(userPaper, competeExam);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error(e.getMessage());
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

    private void doSumbit(UserPaper userPaper, CompeteExam competeExam) {
        // todo 结算
        List<UserPaperAnswer> newUserPaperAnswer = userPaperAnswerService.lambdaQuery()
                .eq(UserPaperAnswer::getUserPaperId, userPaper.getId())
                .list();

        newUserPaperAnswer = newUserPaperAnswer.stream().filter(a -> a.getAnswerId() != null).collect(Collectors.toList());
        long sum = 0;
        for (UserPaperAnswer userPaperAnswer : newUserPaperAnswer) {
            Long questionId = userPaperAnswer.getQuestionId();
            Question question = questionService.getById(questionId);
            if (question == null) {
                continue;
            }
            PaperQuestion paperQuestion = paperQuestionService.lambdaQuery()
                    .eq(PaperQuestion::getQuestionId, question.getId())
                    .eq(PaperQuestion::getPaperId, competeExam.getPaperId()).one();
            List<QuestionAnswer> correctAnswers = questionAnswerService.lambdaQuery().eq(QuestionAnswer::getIsRight, 1).eq(QuestionAnswer::getQuestionId, question.getId()).list();
            List<Long> correctAnswerIds = correctAnswers.stream().map(QuestionAnswer::getId).sorted().collect(Collectors.toList());

            if (question.getType() == 2) {
                // 获取题目的正确答案列表
                // 获取用户的答案列表
                List<UserPaperAnswer> userAnswers = newUserPaperAnswer.stream().filter(a -> a.getQuestionId().equals(question.getId())).collect(Collectors.toList());
                // 将答案ID排序并比较
                List<Long> userAnswerIds = userAnswers.stream().map(UserPaperAnswer::getAnswerId).sorted().collect(Collectors.toList());

                // 如果答案完全匹配，则加分
                if (correctAnswerIds.equals(userAnswerIds)) {
                    sum += paperQuestion.getScore();
                }
            } else {
                if (correctAnswerIds.contains(userPaperAnswer.getAnswerId())) {
                    sum += paperQuestion.getScore();
                }
            }
        }
        userPaper.setTotalScore(sum);
        userPaper.setState("submit");
        userPaperService.updateById(userPaper);
    }
}
